<template>
  <div class="dashboard-container">
    <!-- 左侧菜单 -->
    <div class="sidebar">
      <el-menu
        :default-active="activeMenu"
        class="el-menu-vertical-demo"
        @select="handleMenuSelect"
        router
      >
        <el-menu-item index="/dashboard">
          <el-icon><HomeFilled /></el-icon>
          <span>首页</span>
        </el-menu-item>
        <el-sub-menu index="user">
          <template #title>
            <el-icon><UserFilled /></el-icon>
            <span>人员管理</span>
          </template>
          <el-menu-item index="/user">
            <el-icon><User /></el-icon>
            <span>员工管理</span>
          </el-menu-item>
          <el-menu-item index="/department">
            <el-icon><OfficeBuilding /></el-icon>
            <span>部门管理</span>
          </el-menu-item>
        </el-sub-menu>
        <el-sub-menu index="workflow">
          <template #title>
            <el-icon><Document /></el-icon>
            <span>工作流程</span>
          </template>
          <el-menu-item index="/leave">
            <el-icon><Stamp /></el-icon>
            <span>请假管理</span>
          </el-menu-item>
          <el-menu-item index="/expense">
            <el-icon><Ticket /></el-icon>
            <span>报销管理</span>
          </el-menu-item>
          <el-menu-item index="/attendance">
            <el-icon><Calendar /></el-icon>
            <span>考勤管理</span>
          </el-menu-item>
        </el-sub-menu>
        <el-menu-item index="/task">
          <el-icon><Connection /></el-icon>
          <span>任务管理</span>
        </el-menu-item>
        <el-menu-item index="/settings">
          <el-icon><Setting /></el-icon>
          <span>系统设置</span>
        </el-menu-item>
      </el-menu>
    </div>

    <!-- 右侧内容 -->
    <div class="main-content">
      <!-- 顶部导航栏 -->
      <div class="top-nav">
        <div class="welcome-message">欢迎使用OA办公系统管理端</div>
        <div class="user-info">
          <el-avatar size="small" :src="userInfo.avatarUrl"></el-avatar>
          <span>{{ userInfo.userName }}</span>
          <el-dropdown @command="handleCommand">
            <!-- 使用兼容的 More 图标或 Font Awesome -->
            <el-icon><More /></el-icon>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                <el-dropdown-item command="password">修改密码</el-dropdown-item>
                <el-dropdown-item command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 数据卡片区域 -->
      <div class="stats-cards">
        <el-card class="card-item" shadow="hover" @click="navigateTo('/expense')">
          <div class="card-content">
            <div class="card-icon expense-icon">
              <el-icon><Ticket /></el-icon>
            </div>
            <div class="card-text">
              <div class="card-title">报销待处理</div>
              <div class="card-number">{{ expensePendingCount }}</div>
            </div>
          </div>
          <div class="card-footer">
            <span class="trend-up">
              <i class="el-icon-arrow-up"></i> {{ expenseTrend }}%
            </span>
            <span class="text-muted">较上周</span>
          </div>
        </el-card>

        <el-card class="card-item" shadow="hover" @click="navigateTo('/leave')">
          <div class="card-content">
            <div class="card-icon leave-icon">
              <el-icon><Stamp /></el-icon>
            </div>
            <div class="card-text">
              <div class="card-title">请假待处理</div>
              <div class="card-number">{{ leavePendingCount }}</div>
            </div>
          </div>
          <div class="card-footer">
            <span class="trend-down">
              <i class="el-icon-arrow-down"></i> {{ leaveTrend }}%
            </span>
            <span class="text-muted">较上周</span>
          </div>
        </el-card>

        <el-card class="card-item" shadow="hover" @click="navigateTo('/task')">
          <div class="card-content">
            <div class="card-icon task-icon">
              <el-icon><Connection /></el-icon>
            </div>
            <div class="card-text">
              <div class="card-title">进行中任务</div>
              <div class="card-number">{{ ongoingTaskCount }}</div>
            </div>
          </div>
          <div class="card-footer">
            <span class="trend-up">
              <i class="el-icon-arrow-up"></i> {{ taskTrend }}%
            </span>
            <span class="text-muted">较上周</span>
          </div>
        </el-card>

        <el-card class="card-item" shadow="hover" @click="navigateTo('/user')">
          <div class="card-content">
            <div class="card-icon employee-icon">
              <el-icon><UserFilled /></el-icon>
            </div>
            <div class="card-text">
              <div class="card-title">在职员工</div>
              <div class="card-number">{{ employeeCount }}</div>
            </div>
          </div>
          <div class="card-footer">
            <span class="trend-up">
              <i class="el-icon-arrow-up"></i> {{ employeeTrend }}%
            </span>
            <span class="text-muted">较上月</span>
          </div>
        </el-card>
      </div>

      <!-- 图表区域 -->
      <div class="charts-container">
        <el-card class="chart-card">
          <div class="chart-header">
            <div class="chart-title">考勤异常统计</div>
            <el-select v-model="attendanceTimeRange" size="small" @change="fetchAttendanceData">
              <el-option label="近6个月" value="6m"></el-option>
              <el-option label="近12个月" value="12m"></el-option>
            </el-select>
          </div>
          <div ref="attendanceChartRef" class="chart-content"></div>
        </el-card>

        <el-card class="chart-card">
          <div class="chart-header">
            <div class="chart-title">部门人员分布</div>
            <el-select v-model="departmentType" size="small" @change="fetchDepartmentData">
              <el-option label="按部门" value="department"></el-option>
              <el-option label="按职位" value="position"></el-option>
            </el-select>
          </div>
          <div ref="departmentChartRef" class="chart-content"></div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import * as echarts from 'echarts'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

// 导入图标（使用兼容版本）
import { 
  HomeFilled, 
  UserFilled, 
  User, 
  OfficeBuilding, 
  Document, 
  Stamp, 
  Ticket, 
  Calendar, 
  Connection, 
  Setting,
  ArrowUp,
  ArrowDown,
  More // 使用兼容的 More 图标
} from '@element-plus/icons-vue'

// 路由和菜单状态
const router = useRouter()
const activeMenu = ref('/dashboard')

// 用户信息
const userInfo = ref({
  userName: '管理员',
  avatarUrl: 'https://picsum.photos/40/40'
})

// 数据统计
const expensePendingCount = ref(0)
const leavePendingCount = ref(0)
const ongoingTaskCount = ref(0)
const employeeCount = ref(0)
const expenseTrend = ref(0)
const leaveTrend = ref(0)
const taskTrend = ref(0)
const employeeTrend = ref(0)

// 图表相关
const attendanceChartRef = ref(null)
const departmentChartRef = ref(null)
let attendanceChartInstance = null
let departmentChartInstance = null

// 图表选项
const attendanceTimeRange = ref('6m')
const departmentType = ref('department')

// 模拟API请求函数
const fetchDashboardData = async () => {
  try {
    // 模拟从后端获取数据
    const mockData = {
      expensePending: 3,
      leavePending: 2,
      ongoingTasks: 5,
      employeeCount: 50,
      trends: {
        expense: 2.5,
        leave: -1.8,
        task: 5.3,
        employee: 3.2
      }
    }
    
    // 实际项目中使用这行代码替换上面的模拟数据
    // const { data } = await request.get('/api/dashboard/stats')
    
    expensePendingCount.value = mockData.expensePending
    leavePendingCount.value = mockData.leavePending
    ongoingTaskCount.value = mockData.ongoingTasks
    employeeCount.value = mockData.employeeCount
    
    // 趋势数据
    expenseTrend.value = mockData.trends.expense.toFixed(1)
    leaveTrend.value = Math.abs(mockData.trends.leave).toFixed(1) // 显示绝对值
    taskTrend.value = mockData.trends.task.toFixed(1)
    employeeTrend.value = mockData.trends.employee.toFixed(1)
  } catch (error) {
    console.error('获取仪表盘数据失败:', error)
    ElMessage.error('获取数据失败，请稍后重试')
  }
}

// 获取考勤统计数据
const fetchAttendanceData = async () => {
  try {
    // 模拟从后端获取数据
    const mockData = {
      '6m': {
        months: ['2023-12', '2024-01', '2024-02', '2024-03', '2024-04', '2024-05'],
        values: [12, 8, 15, 10, 7, 5]
      },
      '12m': {
        months: ['2023-06', '2023-07', '2023-08', '2023-09', '2023-10', '2023-11', '2023-12', '2024-01', '2024-02', '2024-03', '2024-04', '2024-05'],
        values: [15, 12, 18, 14, 16, 10, 12, 8, 15, 10, 7, 5]
      }
    }
    
    // 实际项目中使用这行代码替换上面的模拟数据
    // const { data } = await request.get('/api/attendance/stats', { params: { timeRange: attendanceTimeRange.value } })
    
    const data = mockData[attendanceTimeRange.value]
    
    if (attendanceChartInstance) {
      const option = {
        tooltip: { 
          trigger: 'axis',
          formatter: '{b}<br/>异常次数: {c}'
        },
        xAxis: {
          type: 'category',
          data: data.months,
          axisLabel: { color: '#666' }
        },
        yAxis: { 
          type: 'value', 
          axisLabel: { color: '#666' },
          name: '异常次数',
          min: 0
        },
        series: [{
          data: data.values,
          type: 'line',
          smooth: true,
          lineStyle: { color: '#f56c6c', width: 3 },
          areaStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(245, 108, 108, 0.4)' },
            { offset: 1, color: 'rgba(245, 108, 108, 0)' }
          ])},
          itemStyle: {
            color: '#f56c6c',
            borderWidth: 2
          }
        }],
        grid: { top: '15%', bottom: '15%', containLabel: true }
      }
      
      attendanceChartInstance.setOption(option)
    }
  } catch (error) {
    console.error('获取考勤数据失败:', error)
    ElMessage.error('获取考勤数据失败，请稍后重试')
  }
}

// 获取部门统计数据
const fetchDepartmentData = async () => {
  try {
    // 模拟从后端获取数据
    const mockData = {
      department: [
        { name: '研发部', value: 45 },
        { name: '运维部', value: 28 },
        { name: '销售部', value: 32 },
        { name: '行政部', value: 18 },
        { name: '市场部', value: 25 }
      ],
      position: [
        { name: '经理', value: 10 },
        { name: '主管', value: 15 },
        { name: '专员', value: 60 },
        { name: '助理', value: 25 }
      ]
    }
    
    // 实际项目中使用这行代码替换上面的模拟数据
    // const { data } = await request.get('/api/department/stats', { params: { type: departmentType.value } })
    
    const data = mockData[departmentType.value]
    
    if (departmentChartInstance) {
      const option = {
        tooltip: { 
          trigger: 'item',
          formatter: '{b}: {c}人 ({d}%)'
        },
        legend: { 
          orient: 'vertical', 
          left: 'right', 
          textStyle: { color: '#666' },
          type: 'scroll'
        },
        series: [{
          type: 'pie',
          radius: ['40%', '70%'],
          data: data.map(item => ({ 
            value: item.value, 
            name: item.name,
            itemStyle: { 
              color: `hsl(${(data.indexOf(item) * 60) % 360}, 70%, 60%)`   
            }
          })),
          label: { 
            show: true, 
            formatter: '{b}: {d}%',
            textStyle: {
              fontSize: 12
            }
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }
      
      departmentChartInstance.setOption(option)
    }
  } catch (error) {
    console.error('获取部门数据失败:', error)
    ElMessage.error('获取部门数据失败，请稍后重试')
  }
}

// 处理菜单选择
const handleMenuSelect = (key) => {
  activeMenu.value = key
  router.push(key)
}

// 导航到指定页面
const navigateTo = (path) => {
  router.push(path)
}

// 处理用户命令
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'password':
      router.push('/change-password')
      break
    case 'logout':
      // 处理退出登录逻辑
      break
  }
}

// 窗口大小变化时重绘图表
const handleResize = () => {
  attendanceChartInstance?.resize()
  departmentChartInstance?.resize()
}

onMounted(() => {
  // 初始化图表
  attendanceChartInstance = echarts.init(attendanceChartRef.value)
  departmentChartInstance = echarts.init(departmentChartRef.value)
  
  // 获取数据并渲染图表
  fetchDashboardData()
  fetchAttendanceData()
  fetchDepartmentData()
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  // 清理资源
  window.removeEventListener('resize', handleResize)
  attendanceChartInstance?.dispose()
  departmentChartInstance?.dispose()
})
</script>

<style scoped>
.dashboard-container {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

.sidebar {
  width: 220px;
  background-color: #f5f7fa;
  border-right: 1px solid #e6e6e6;
  overflow-y: auto;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.top-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
  padding: 0 20px;
  background-color: #fff;
  border-bottom: 1px solid #e6e6e6;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.welcome-message {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  padding: 20px;
}

  .card-item {
    height: 180px;
    transition: transform 0.3s, box-shadow 0.3s;
  }

  .card-item:hover {
    transform: translateY(-5px);
  }

  .card-content {
    display: flex;
    align-items: center;
    gap: 20px;
    padding: 20px;
  }

  .card-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 24px;
  }

  .expense-icon {
    background-color: #f1c40f;
  }

  .leave-icon {
    background-color: #9b59b6;
  }

  .task-icon {
    background-color: #3498db;
  }

  .employee-icon {
    background-color: #27ae60;
  }

  .card-text {
    flex: 1;
  }

  .card-title {
    font-size: 16px;
    color: #606266;
    margin-bottom: 10px;
  }

  .card-number {
    font-size: 32px;
    font-weight: 600;
    color: #303133;
  }

  .card-footer {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 0 20px;
    color: #909399;
    font-size: 14px;
  }

.trend-up {
  color: #f56c6c;
}

.trend-down {
  color: #67c23a;
}

.charts-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  padding: 0 20px 20px;
}

.chart-card {
  height: 400px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-content {
  height: calc(100% - 60px);
  padding: 10px;
}

.text-muted {
  color: #909399;
}

@media (max-width: 1200px) {
  .charts-container {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .sidebar {
    display: none;
  }
  
  .welcome-message {
    font-size: 16px;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
  }
}
</style>    